package com.twodstar.match5;

import org.libsdl.app.SDLActivity;
import com.chartboost.sdk.Chartboost;
import com.chartboost.sdk.ChartboostDelegate;
import com.nextpeer.android.Nextpeer;
import com.nextpeer.android.NextpeerListener;
import com.nextpeer.android.NextpeerSettings;
import com.nextpeer.android.NextpeerTournamentEndData;
import com.nextpeer.android.NextpeerTournamentStartData;

//import com.letang.adunion.JoyBannerAdPosition;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;





/**
    SDL Activity
*/
@SuppressLint("NewApi")
public class GameActivity extends      SDLActivity implements ChartboostDelegate
									// Activity implements OnClickListener  
{ 
	public static boolean m_RemapCoordinates = false;
	public static int m_CurrentLevel = 1;
	private Chartboost cb;
	
	// should be same with selipner_android.h
	enum FUNCTION
	{
		FUNC_UNUSED1,
		FUNC_UNUSED2,
		FUNC_UNUSED3,
		FUNC_UNUSED4,
		FUNC_UNUSED5,
		FUNC_UNUSED6,
		FUNC_UNUSED7,
		FUNC_UNUSED8,
		FUNC_UNUSED9,
		FUNC_UNUSED10,
		
		FUNC_AdInit,
		FUNC_AdResume,
		FUNC_AdShoutdown,
		FUNC_AdRequestBanner,
		FUNC_AdCloseBanner,
		FUNC_AdRequestFullScreen,
		FUNC_gotoURL,
		FUNC_onHardQuit,
		
		FUNC_NEXTPEER_Init,
		FUNC_NEXTPEER_LaunchDashboard,
		FUNC_NEXTPEER_ShutDown,
		FUNC_NEXTPEER_ReportScore,
		FUNC_NEXTPEER_ReportForfeitForCurrentTournament,
		FUNC_NEXTPEER_ReportControlledTournamentOver,
		FUNC_NEXTPEER_SetCurrentTournament,
		
	};
	
	// Will be used by Nextpeer to report on various events
    private NextpeerListener _nextpeerListener = new NextpeerListener() 
    {
        /* NextpeerListener mandatory methods */
    	private String[] m_TournamentIDs = {  	"NPA23926321092678092", "NPA239263210931846528", "NPA239263210931918715", "NPA239263210931918738", "NPA239263210931918745", 
								    			"NPA239263210931918754", "NPA239263210931918763", "NPA239263210931918770", "NPA239263210931918774", "NPA239263210931918777", 
								    			"NPA239263210931919795", "NPA239263210931919813", "NPA239263210931919819", "NPA239263210931919838", "NPA239263210931919843", 
								    			"NPA239263210931919855", "NPA239263210931919865", "NPA239263210931919871", "NPA239263210931919884", "NPA239263210931919896", 
								    			"NPA239263210931919903", "NPA239263210931919910", "NPA239263210931919920", "NPA239263210931919929", "NPA239263210931919936", 
								    			"NPA239263210931919940", "NPA239263210931919948", "NPA239263210931919957", "NPA239263210931919973", "NPA239263210931919981", 
								    			"NPA239263210931919995", "NPA239263210931920007", "NPA239263210931920024", "NPA239263210931920041", "NPA239263210931920046", 
								    			"NPA239263210931920058", "NPA239263210931920065", "NPA239263210931920073", "NPA239263210931920079", "NPA239263210931920090", 
								    			"NPA239263210931920116", "NPA239263210931920127", "NPA239263210931920139", "NPA239263210931920150", "NPA239263210931920235", 
								    			"NPA239263210931920253", "NPA239263210931920265", "NPA239263210931920278", "NPA239263210931920293", "NPA239263210931920306", 
								    			"NPA239263210931920321", "NPA239263210931920333", "NPA239263210931920342", "NPA239263210931920358", "NPA239263210931920366", 
								    			"NPA239263210931920377", "NPA239263210931920385", "NPA239263210931920394", "NPA239263210931920401", "NPA239263210931920411", 
								    			"NPA239263210931920420", "NPA239263210931920428", "NPA239263210931920437", "NPA239263210931920440", "NPA239263210931920455", 
								    			"NPA239263210931920464", "NPA239263210931920468", "NPA239263210931920473", "NPA239263210931920485", "NPA239263210931920496", 
								    			"NPA239263210931920522", "NPA239263210931920530", "NPA239263210931920552", "NPA239263210931920563", "NPA239263210931920569", 
								    			"NPA239263210931920577", "NPA239263210931920584", "NPA239263210931920594", "NPA239263210931920604", "NPA239263210931920613", 
								    			"NPA239263210931920624", "NPA239263210931920638", "NPA239263210931920651", "NPA239263210931920664", "NPA239263210931920670", 
								    			"NPA239263210931920683", "NPA239263210931920691", "NPA239263210931920702", "NPA239263210931920714", "NPA239263210931920724", 
								    			"NPA239263210931920745", "NPA239263210931920759", "NPA239263210931920782", "NPA239263210931920866", "NPA239263210931920957", 
								    			"NPA239263210931920968", "NPA239263210931920975", "NPA239263210931920982", "NPA239263210931920999", "NPA239263210931921031",	
    										};

		@Override
		public void onTournamentEnd(NextpeerTournamentEndData arg0) 
		{
			// TODO Auto-generated method stuby
			
		}

		@Override
		public void onTournamentStart(NextpeerTournamentStartData arg0) 
		{
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public boolean onSupportsTournament(String tournamentUuid) 
		{
			//Log.v("log:", "support? this tournament : " + tournamentUuid);
			String CurrentID = "NPA23926321092678092";
			CurrentID = m_TournamentIDs[m_CurrentLevel - 1];
			//Log.v("log:", "tournament ID: " + CurrentID);
			
		    if (TextUtils.equals(tournamentUuid, CurrentID)) 
		    {
		        return true;
		    }
		    else 
		    {		    	
		        // We don't know this tournament, better not support it
		        return false;
		    }
		}	
		
		
    };
    
    

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy()
	{
		//AdunionIns.GetInstance(this).DestroyAd();
		// TODO Auto-generated method stub
		super.onDestroy();
		this.cb.onDestroy(this);
		
	}
	
	@Override
	protected void onStop()
	{
		super.onStop();
		if (Nextpeer.isCurrentlyInTournament()) 
		{ 
	        Nextpeer.reportForfeitForCurrentTournament();	        
	    }
		this.cb.onStop(this);
	}
	
	@Override
	public void onBackPressed() 
	{

	    // If an interstitial is on screen, close it. Otherwise continue as normal.
	    if (this.cb.onBackPressed())
	    {
	    	if(this.cb.hasCachedInterstitial()== false)
	        {
	        	cb.cacheInterstitial();
	        }
	        return;
	    }
	    else
	        super.onBackPressed();
	}
	
	@Override
    protected void onResume() 
	{
      
        super.onResume();
        if(this.cb.hasCachedInterstitial()== false)
        {
        	cb.cacheInterstitial();
        }
    }
	
	 @Override
	 protected void onCreate(Bundle savedInstanceState) 
	 {
	        //Log.v("SDL", "onCreate()");
		super.onCreate(savedInstanceState);
		
     
        Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int orientation = getScreenOrientation(display);
        int rotation = display.getRotation();
        
        m_RemapCoordinates  = (orientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_0) ||
                (orientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_180) ||
                (orientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_90) ||
                (orientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_270);    
       
		    
		this.cb = Chartboost.sharedChartboost();
		String appId = "52d370ac9ddc356767992831";
		String appSignature = "b8f67d0b359dd728034ea32906259c68de1268a5";
		this.cb.onCreate(this, appId, appSignature, null);
	 }
	 
	 @Override
	 protected void onStart() 
	 {
	     super.onStart();
	     this.cb.onStart(this);
	 }

	
	//---------------------------------------

	private void AdInit() 
	{
		this.cb.setImpressionsUseActivities(true);
		this.cb.startSession();
		this.cb.cacheInterstitial();		
    }
	
	private static void AdResume() 
	{
		//AdunionIns.GetInstance(mSingleton).ResumeAd();
		
    }
	
	private void AdShutdown() 
	{
		
		//AdunionIns.GetInstance(mSingleton).DestroyAd();
		
    }
	
	private void AdRequestBanner() 
	{
		//Log.w("Adunion", "Requesting Banner");
		//AdunionIns.GetInstance(mSingleton).ShowBannerAd(JoyBannerAdPosition.POS_MID_BOTTOM);
		
    }
	
	private void AdCloseBanner() 
	{
		//AdunionIns.GetInstance(mSingleton).CloseBannerAd();
	}
	
	/*
	 * gamestart---- Display advertising in the beginning of the game                                                      
	 * gamepause---- Display ads in the game is paused              
	 * gameexit---- Display ads at the end of the game   
	 */
	private void AdRequestFullScreen(int Type) 
	{
		//if(Type == 1)
		//	AdunionIns.GetInstance(mSingleton).ShowAds("gamestart");s
		//else if(Type == 2)
		//	AdunionIns.GetInstance(mSingleton).ShowAds("gamepause");
		//else if(Type == 3)
		//	AdunionIns.GetInstance(mSingleton).ShowAds("gameexit");		
		Log.w("log:", "Full Screen Ad");
		if(this.cb.hasCachedInterstitial())
		{
			this.cb.showInterstitial();
			//SDLActivity.handlePause();
		}
		else
		{
			cb.cacheInterstitial();
		}
    }
	
	
	enum URL_TYPE
	{
		URL_TYPE_RATEUS,
		URL_TYPE_MOREGAMES,
		URL_TYPE_FACEBOOK,
		URL_TYPE_TWITTER,
		URL_TYPE_2DSTAR,
	};
	
	private void gotoURL(int Type)
	{
		Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=" + getContext().getPackageName());;
		
				
		if( Type == URL_TYPE.URL_TYPE_RATEUS.ordinal() )
			uri = Uri.parse("https://play.google.com/store/apps/details?id=" + getContext().getPackageName());
		
		else if( Type == URL_TYPE.URL_TYPE_MOREGAMES.ordinal() )
			uri = Uri.parse("http://list.mobappbox.com/android?language=en&tag=mobappbox");
		
		else if( Type == URL_TYPE.URL_TYPE_FACEBOOK.ordinal() )
			uri = Uri.parse("http://www.facebook.com/2DStar");
		
		else if( Type == URL_TYPE.URL_TYPE_TWITTER.ordinal() )
			uri = Uri.parse("https://twitter.com/2dstar");
		
		else if( Type == URL_TYPE.URL_TYPE_2DSTAR.ordinal() )
			uri = Uri.parse("http://www.2dstar.com");
		
		
	    Intent externalLink = new Intent(Intent.ACTION_VIEW, uri);
	    
	    try {
	        	getContext().startActivity(externalLink);
	        	
	    	} 
	    	catch (ActivityNotFoundException e) 
	    	{
	    		Log.w("RateApp", "Error Redirecting to external Link");
	    	}
	}
	
	private void onHardQuit()
	{
		System.exit(0);
	}
	
	private void NextPeerInit()
    {
		NextpeerSettings settings = new NextpeerSettings();
		//settings.inGameNotificationPosition = settings.inGameNotificationPosition.BOTTOM;
		//settings.inGameNotificationAlignment = NextpeerRankingDisplayAlignment.HORIZONTAL;
		//settings.inGameNotificationPosition = NextpeerRankingDisplayPosition.TOP_RIGHT;
		//settings.inGameNotificationStyle = NextpeerRankingDisplayStyle.LIST;
		
    	 Nextpeer.initialize(this, "b15097bb75e008c39e84e3ae4ab8dd63", _nextpeerListener, settings);
    	 Nextpeer.onStart();
    }
    
    private void NextPeerLaunchDashBoard()
    {
    	if(Nextpeer.isNextpeerInitialized() == false)
    		NextPeerInit();
    		
    	Nextpeer.launch();
    }
    
    private void NextPeerShutDown()
    {
    	// how to release?
    }
    
    private void NextPeerReportForfeitForCurrentTournament()
    {
    	if(Nextpeer.isCurrentlyInTournament())
    	{
    		Nextpeer.reportForfeitForCurrentTournament();
    	}
    }
    
    private void ReportControlledTournamentOver(int Score)
    {
    	Nextpeer.reportControlledTournamentOverWithScore(Score);
    }
    
    private void NextpeerReportScore(int Score)
    {
    	Nextpeer.reportScoreForCurrentTournament(Score);
    }
    
	
	
	@Override
	 protected boolean onUnhandledMessage(int command, Object param) 
	{
		switch( FUNCTION.values()[command]  )
		{
			case FUNC_AdInit:
				AdInit();
				return true;
				
			case FUNC_AdResume:
				AdResume();
				return true;
				
			case FUNC_AdShoutdown:
				AdShutdown();
				return true;
				
			case FUNC_AdRequestBanner:
				AdRequestBanner();
				return true;
				
			case FUNC_AdCloseBanner:
				AdCloseBanner();
				return true;
				
			case FUNC_AdRequestFullScreen:
				AdRequestFullScreen((Integer) param);
				return true;
				
			case FUNC_gotoURL:
				gotoURL((Integer) param);
				return true;
				
			case FUNC_onHardQuit:
				onHardQuit();
				return true;
				
			case FUNC_NEXTPEER_Init:
				NextPeerInit();
				return true;
				
			case FUNC_NEXTPEER_LaunchDashboard:
				NextPeerLaunchDashBoard();
				return true;
			
			case FUNC_NEXTPEER_ShutDown:
				NextPeerShutDown();
				return true;
				
			case FUNC_NEXTPEER_ReportScore:
				NextpeerReportScore((Integer)param);
				return true;
				
			case FUNC_NEXTPEER_ReportForfeitForCurrentTournament:
				NextPeerReportForfeitForCurrentTournament();
				return true;
			
			case FUNC_NEXTPEER_ReportControlledTournamentOver:
				ReportControlledTournamentOver((Integer)param);
				return true;
				
			case FUNC_NEXTPEER_SetCurrentTournament:
				m_CurrentLevel = (Integer)param;
				Log.v("log", "current level tournament : " + m_CurrentLevel);
			
			default:
				 return false;
		
		}
	       
	}


	/*
	
	protected void onCallFunction(int FunctionID, int Para1, int Para2, int Para3)
	{
		
		
	}
	*/

	@SuppressWarnings("deprecation")
	public static int getScreenOrientation(Display display)
    {
		int width = 0;
		 int height = 0;
		 
		if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13 ) 
		{

	         width = display.getWidth();
	         height = display.getHeight();
		}
		else
	    {
		  Point size = new Point();
		  display.getSize(size);
		  width = size.x;
		  height = size.y;
	    }
		

        int orientation;
       
        if(width <= height)
        {
        	orientation = Configuration.ORIENTATION_PORTRAIT;
        }
        else
        { // if it is not any of the above it will defineitly be landscape
        	orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
           
        return orientation;
    }
	
	@Override
	public void didDismissInterstitial(String location) 
	{
	    cb.cacheInterstitial(location);
	    //SDLActivity.handleResume();
	}
	

	@Override
	public void didCacheInterstitial(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didCacheMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didClickInterstitial(String arg0) {
		// TODO Auto-generated method stub
		//SDLActivity.handleResume();
		if(this.cb.hasCachedInterstitial()== false)
        {
        	cb.cacheInterstitial();
        }
	}

	@Override
	public void didClickMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didCloseInterstitial(String arg0) 
	{
		// TODO Auto-generated method stub
		//SDLActivity.handleResume();
		if(this.cb.hasCachedInterstitial()== false)
        {
        	cb.cacheInterstitial();
        }
	}

	@Override
	public void didCloseMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didDismissMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didFailToLoadInterstitial(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didFailToLoadMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didFailToLoadUrl(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void didShowInterstitial(String arg0) {
		// TODO Auto-generated method stub
		if(this.cb.hasCachedInterstitial()== false)
        {
        	cb.cacheInterstitial();
        }
	}

	@Override
	public void didShowMoreApps() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean shouldDisplayInterstitial(String arg0) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean shouldDisplayLoadingViewForMoreApps() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean shouldDisplayMoreApps() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean shouldRequestInterstitial(String arg0) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean shouldRequestInterstitialsInFirstSession() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean shouldRequestMoreApps() {
		// TODO Auto-generated method stub
		return false;
	}

}
